<template>
  <div class="container">
    <div class="body">
      <div class="common-header">
        <!-- <div class="alibaba-design" /> -->
        <!-- <div class="uncan-2019-text" /> -->
        <!-- <div class="uncan-right" /> -->
        <div class="title-status">
          {{orderStatus}}
        </div>
      </div>
      <div class="remain-time" v-if="ticketInfo.head.status === 0">
        <div class="remain-time-name">
          剩余时间
        </div>
        <flipDown v-if="countdown" :countdown="countdown" :onEnd="getOrderDetail" :id="id" />
      </div>
      <div class="title-description" v-if="ticketInfo.head.status !== 1">
        温馨提示: 超出限定时间未完成支付, 系统将自动关闭交易
      </div>
      <acquireTicket v-if="ticketInfo.head.status === 1" :out-sea="outSea" />
      <template v-if="ready && showDetail">
        <!-- 订单未支持的才允许修改用票人 -->
        <co-list v-if="ticketInfo.head.orderType==1" style=" border: 1px solid rgba(61, 61, 61, 0.8);margin-bottom:16px; " form>
          <co-list-item>
            <span class="forward-give-form-label">
              姓名
            </span>
            <co-input :readonly="true" :value="ticketInfo.head.pname" slot="right" placeholder="" />
          </co-list-item>
          <co-list-item>
            <span class="forward-give-form-label">
              手机号码
            </span>
            <co-input :readonly="true" :value="ticketInfo.head.phone" />
          </co-list-item>
          <co-list-item>
            <span class="forward-give-form-label">
              公司名称
            </span>
            <co-input :readonly="true" :value="ticketInfo.head.cname" slot="right" placeholder="请输入" />
          </co-list-item>
        </co-list>
        <ticketCard v-for="(ticket,index) in ticketInfo.body_ticket" :ticket="ticket" :readonly="ticketInfo.head.status !== 0" :key="index" :head="ticketInfo.head" :orderType="ticketInfo.head.orderType||0" :activityId="ticketInfo.head.projectId||''" />
      </template>
      <totalPrice v-if="ready" :totalPrice="ticketInfo.head.money" :showDetail="showDetail" :toggleDetail="toggleDetail" :billlcode="ticketInfo.head.billlcode" />
      <orderInfo v-if="ready && showDetail" :orderInfo="ticketInfo.head" />
      <payType />


    </div>
    <div>
      <div class="ticketKnow-box" v-if="showPayTips && ticketInfo.head.status === 0">
        <div class="ticketKnow maxWidth">
          <div class="ticketKnow-tit-box">
            <!--<span style="color: #fff;background: red;border-radius: 10px;width: 17px;height: 17px;text-align: center;display: inline-block">！</span>-->
            <span>&nbsp;&nbsp;&nbsp;&nbsp;您的钉钉还不是最新版本，请升级至最新版本，或点击右上角“更多”，打开浏览器继续完成支付哦</span>
          </div>
        </div>
      </div>
      <div class="bottom-buttons" v-if="ticketInfo.head.status === 0">
        <co-button class="close-action" color="disabled" @click="closeOrder">
          关闭订单
        </co-button>
        <co-button class="pay-action" color="primary" @click="pay" :loading="pending">
          确认支付
        </co-button>
      </div>
    </div>
    <!-- 防止用户从我的门票进来 -->
    <!-- <div class="bottom-buttons" v-else-if="[2,3,4].indexOf(ticketInfo.head.status) > -1">
      <co-button class="close-action" color="disabled" @click="quit">
        退出
      </co-button>
      <co-button class="pay-action" color="primary" @click="recreateOrder">
        重新下单
      </co-button>
    </div> -->
  </div>
</template>

<script>
import ticketCard from "./ticketCard";
import totalPrice from "./totalPrice";
import orderInfo from "./orderInfo";
import payType from "./payType";
import flipDown from "./flipDown";
import acquireTicket from "./acquireTicket";
import ddApi from "./../mine/ddApi";

import { ORDER_TITLE_TEXT } from "./constants";
import * as dd from 'dingtalk-jsapi';
import service from "../../api/order";
import serviceInvoice from "./../../api/invoice";
import { jwtFun } from "@/router/publicJs/jwt";

export default {
  name: "OrderDetail",
  components: {
    ticketCard,
    totalPrice,
    orderInfo,
    payType,
    flipDown,
    acquireTicket
  },
  data() {
    return {
      showPayTips: false, //是否展示提示框
      thisPhone: "", //当前登录人手机号
      invoiceDetails: {}, //发票详情
      outSea: false,
      id: "",
      ticketInfo: {
        body_ticket: [],
        head: {}
      },
      ready: false,
      pending: false,
      // 是否显示完整的详情数据
      showDetail: false
    };
  },
  computed: {
    countdown() {
      if (this.ticketInfo.head.countdownPayment) {
        const now = new Date();
        const { createTime, countdownPayment } = this.ticketInfo.head;
        const secondsTillNow =
          (createTime + countdownPayment * 60 * 1000 - now.getTime()) / 1000;
        return secondsTillNow > 0 ? secondsTillNow : null;
      } else {
        return null;
      }
    },
    orderStatus() {
      if (this.ticketInfo.head.status !== undefined) {
        return ORDER_TITLE_TEXT[this.ticketInfo.head.status];
      } else {
        return "";
      }
    }
  },
  created() {
    // // 为了测试
    // sessionStorage.setItem("billlcodeUcan", 27);
    // this.id = sessionStorage.getItem("billlcodeUcan");
    this.id =
      this.$route.query.billlcode || sessionStorage.getItem("billlcodeUcan");
    if (!this.id) {
      this.$toast("必要参数丢失");
      this.$router.go(-1);
      return;
    }
    sessionStorage.setItem("billlcodeUcan", this.id);
    this.getThisPhone();

  },
  mounted(){
    this.isShowTips();
  },
  methods: {
    async isShowTips() {
      const isDd = dd.env.platform !== 'notInDingTalk'
      if (!isDd) {
        this.showPayTips = true;
        return false
      }
      const isAndroid = navigator.userAgent.toLowerCase().indexOf("android") !== -1;
      const isLow = await ddApi.watchDDFersion2();
      if (isAndroid &&isLow) {
        this.showPayTips = true
      }
    },
    // 获取当前登录人手机号
    async getThisPhone() {
      this.thisPhone = (await jwtFun()).linkphone;
      this.getOrderDetail(this.id);
    },
    getOrderDetail(id) {
      // {"success":true,"errorCode":null,"errorMsg":null,"result":{"head":{"orderId":43630,"projectId":23,"billtype":1,"billlcode":"4AF16515N1Q6","payway":null,"status":0,"psnId":null,"pname":"负责人","cname":"公司名称","countryCode":"86","phone":"15972961091","vnote":"备注","userId":8,"updateTime":1559013098000,"createTime":1559032638000,"isDel":0,"num":null,"money":0.5,"invoiceStatus":null,"countdownPayment":30,"orderType":1,"pricegroupId":11,"pricegroupName":"价格组名称","total":3,"totalPriceoriginalPrice":300.00,"totalCurrentPrice":0.50},"invoice":[],"body_ticket":[{"type_name":"aa","type_sdate":1554566400000,"type_mny":0.1,"type_id":43726,"type_typeDate":"06:04-06:10","type_spice":0.1,"ticket_psn":[],"type_edate":1555344000000,"type_numm":1,"type_url":"https://static.dingtalk.com/media/lALPDeC2t_udxU3NAQ7NAQ4_270_270.png"},{"type_name":"票名","type_sdate":1555430400000,"type_mny":0.2,"type_id":43727,"type_typeDate":"06:03-06:46","type_spice":0.2,"ticket_psn":[],"type_edate":1556121600000,"type_numm":1,"type_url":"https://static.dingtalk.com/media/lALPDgQ9qphEDPLNAoDNAoI_642_640.png"},{"type_name":"啊啊啊","type_sdate":1556035200000,"type_mny":0.2,"type_id":43728,"type_typeDate":"06:02-06:04","type_spice":0.2,"ticket_psn":[],"type_edate":1556640000000,"type_numm":1,"type_url":"https://static.dingtalk.com/media/lALPDgQ9qphFsf7NAoDNAoI_642_640.png"}]},"arguments":null}
      // {"success":true,"errorCode":null,"errorMsg":null,"result":{"head":{"orderId":44034,"projectId":24,"billtype":0,"billlcode":"4AEP7TNEAL2S","payway":null,"status":0,"psnId":null,"pname":"默认价格组","cname":null,"countryCode":"86","phone":"15972961091","vnote":null,"userId":2816,"updateTime":1556004036000,"createTime":1558945286000,"isDel":0,"num":null,"money":0.01,"invoiceStatus":null,"countdownPayment":30},"invoice":[],"body_ticket":[{"type_name":"普通票","type_sdate":1555948800000,"type_mny":0.01,"type_id":44148,"type_typeDate":"07:00-09:00","type_spice":0.01,"ticket_psn":[{"id":4965,"psnId":2816,"vnote1":null,"vnote2":null,"vnote3":null,"vnote4":null,"vnote5":null,"vnote6":null,"isDel":0,"creatDate":1558945279000,"updateDate":1558945279000,"formJson":"[{\"attribute\":{\"filedValue\":\"chen\",\"filedCode\":\"uName\",\"titName\":\"姓名\",\"placeholder\":\"请输入\",\"maxLength\":20,\"ifCheck\":true},\"componentName\":\"stringTem\"},{\"attribute\":{\"filedValue\":\"13545006099\",\"filedCode\":\"uTel\",\"titName\":\"手机号\",\"placeholder\":\"请输入\",\"maxLength\":11,\"ifCheck\":true,\"areaCode\":\"86\"},\"componentName\":\"stringTem\"},{\"attribute\":{\"filedValue\":\"13545006099@\",\"filedCode\":\"uEmail\",\"titName\":\"使用人邮箱\",\"placeholder\":\"请输入\",\"maxLength\":20,\"ifCheck\":true},\"componentName\":\"stringTem\"},{\"attribute\":{\"filedValue\":\"13545006099\",\"filedCode\":\"uIdCard\",\"titName\":\"使用人身份证\",\"placeholder\":\"请输入\",\"maxLength\":20,\"ifCheck\":true},\"componentName\":\"stringTem\"}]"}],"type_edate":1557417600000,"type_numm":1,"type_url":"https://static.dingtalk.com/media/lADPDeC2uBoxz9XOAG4ASc4AIABd_2097245_7209033.jpg"}]},"arguments":null}
      service
        .getOrderDetail({ billlcode: id })
        .then(res => {
          const {
            result: { body_ticket = [], head }
          } = res;
          this.ticketInfo = {
            body_ticket,
            head
          };
          this.outSea = !~["86", "886", "853", "852"].indexOf(head.countryCode);
          // 除未支付外, 所有订单默认展示详情
          this.showDetail = head.status !== 0;
          this.ready = true;
          if (this.ticketInfo.head.status == 1) {
            // 只有status==1 支付成功的时候才去查
            let activityIdList = [33, 23, 45, 52, 72, 73, 74]; //projectId 等效于activityId 33=云栖大会  23=本地测试 45=杭州小分队 52程阳预发测试 72钉钉发布会 73钉钉发布会测试 74 云原生大会
            if (activityIdList.indexOf(this.ticketInfo.head.projectId) != -1) {
              // 设置只有部分活动才可以申请发票
              // let zhuansongList = [
              //   "15972961091",
              //   "13758141708",
              //   "15868154582",
              //   "13127882837",
              //   "18621532154",
              //   "17623878198",
              //   "15855431282",
              //   "1760130268995005"
              // ];
              // if (zhuansongList.indexOf(this.thisPhone) != -1) {
              //   // 测试阶段设置先只能部分人可以看见
              //   this.invoiceStatus();
              // }
              this.invoiceStatus();
            }
          }
          console.log(this.ticketInfo);
        })
        .catch(err => {
          console.log(err);
        });
    },
    // 查看发票的状态（只有status==1 支付成功的时候才去查）
    invoiceStatus() {
      //  状态 0已申请 1开票中 2开票成功 3已发货 -1失败 -2默认的（自己填写的）
      console.log("orderId", this.ticketInfo.head.orderId);
      serviceInvoice
        .queryInvoiceByTicketOrderIdForMob(this.ticketInfo.head.orderId)
        .then(res => {
          console.log("res===", res);
          if (res.success && res.result.length == 0) {
            this.$set(this.ticketInfo.head, "invoiceStatus", -2); //此处如果结果没有值则默认是-2
          }

          if (res.result && res.result.length != 0) {
            const result = res.result[0];
            console.log("result", result);
            this.invoiceDetails = result;
            let invoiceStatus = result.status;
            if (invoiceStatus === null) {
              invoiceStatus = -2;
            }
            this.$set(this.ticketInfo.head, "invoiceStatus", invoiceStatus); //此处如果结果没有值则默认是-2
          }
        });
    },
    // 申请发票(子组件调用)
    invoicePage() {
      const invoiceStatus = this.ticketInfo.head.invoiceStatus;
      if (invoiceStatus == -2 || invoiceStatus == -1) {
        console.log("orderId", this.ticketInfo.head.orderId);
        this.$router.push({
          name: "InvoiceForm",
          query: {
            billlcode: this.ticketInfo.head.billlcode,
            totalPrice: this.ticketInfo.head.money,
            orderId: this.ticketInfo.head.orderId,
            projectId: this.ticketInfo.head.projectId
          }
        });
      } else if (invoiceStatus === 0) {
        // this.$toast("已提交申请，请耐心等待");
        this.$toast("发票将于大会结束后3-5个工作日发送");
      } else if (invoiceStatus == 1) {
        this.$toast("发票将于大会结束后3-5个工作日发送");
      } else if (invoiceStatus == 2 || invoiceStatus == 3) {
        this.$router.push({
          name: "myInvoice",
          query: {
            id: this.invoiceDetails.id
            // formData: {
            //   ...this.invoiceDetails
            // }
          }
        });
      } else if (invoiceStatus == 4) {
        this.$toast("已退款");
      }
    },
    toggleDetail() {
      this.showDetail = true;
    },
    pay() {
      // 支付
      this.pending = true;
      service
        .pay({
          out_trade_no: this.ticketInfo.head.billlcode,
          total_amount: this.ticketInfo.head.money,
          subject: this.ticketInfo.head.pname,
          body: this.ticketInfo.head.vnote,
          return_url: window.location.href
        })
        .then(res => {
          console.log(res);
          const { result = "" } = res;
          document.write(result);
        })
        .catch(err => {
          this.pending = false;
          console.log(err);
        });
    },
    async closeOrder() {
      const isConfirm = await this.$confirm("您确定进行关闭？", {
        title: "温馨提示",
        okLabel: "确认关闭",
        cancelLabel: "取消",
        showCancel: true
      });
      if (!isConfirm) {
        return;
      }

      // 关闭订单
      service
        .close({
          billlcode: this.ticketInfo.head.billlcode,
          status: this.ticketInfo.head.status
        })
        .then(res => {
          this.getOrderDetail(this.id);
        })
        .catch(err => {
          console.log(err);
        });
    },
    recreateOrder() {
      // 重新下单
      this.$router.replace({
        name: "buyTicketHome"
      });
    },
    quit() {
      // 退出
      this.$router.replace({
        name: "buyTicketHome"
      });
    }
  }
};
</script>

<style scoped lang="scss">
.container {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  overflow-y: auto;
  overflow-x: hidden;
  display: flex;
  flex-direction: column;
  justify-content: space-between;

  .body {
    width: 100%;
    box-sizing: border-box;
    padding: 0 30px;

    .common-header {
      width: 100%;
      height: 285px;
    }

    .remain-time {
      width: 100%;
      display: flex;
      flex-direction: row;
      justify-content: left;
      align-items: center;

      .remain-time-name {
        font-size: 22px;
        color: #c7c3c3;
        margin-right: 19px;
      }
    }
  }

  .bottom-buttons {
    height: 110px;
    position: relative;
    width: 100vw;
    max-width: 1480px;
    left: 0;
    bottom: 0;
    display: flex;

    .close-action {
      flex: 1 1 35%;
      border-radius: 0;
    }
    .pay-action {
      flex: 1 1 65%;
      border-radius: 0;
    }
  }

  .ticketKnow-box {
    width: 100%;
    height: auto;
    position: relative;
    left: 0px;
    bottom: 0;
    background: #1b1b20;
  }
  .ticketKnow {
    width: 100%;
    height: auto;
    margin: auto;
    max-height: 360px;
    overflow-y: auto;
  }
  .ticketKnow-tit-box {
    width: 100%;
    height: auto;
    background: #1b1b20;
    margin-bottom: 16px;
    padding: 16px;
    font-size: 20px;
    color: #fff;
    opacity: 0.6;
    /* background: #ffffff; */
    text-align: left;
    z-index: 2;
    &:before {
      content: '';
      position: absolute;
      top: 20px;
      left: 19px;
      width: 22px;
      height: 22px;
      background: center / contain url("https://gw.alicdn.com/tfs/TB1jOwtH4jaK1RjSZKzXXXVwXXa-16-22.svg") no-repeat;
    }
  }
}
</style>
